<template>
	<view>
		<image src="../../../static/me/bg1.jpg" mode="" style="position: fixed;top: 0; left: 0;width: 100vw; height: 100vh;"></image>
		<view style="z-index: 100;position: absolute;width: 100vw;padding-left: 5px;">
			<view style="margin: 20rpx 10rpx 0; font-size: 40rpx">
				<view>{{ address ? address.dorm + address.room : '' }}</view>
			</view>

			<picker-view v-if="showPickerView" :value="values" @change="bindChange">
				<picker-view-column>
					<view class="item" v-for="(item, index) in dorms" :key="index">{{ item }}</view>
				</picker-view-column>
				<picker-view-column>
					<view class="item" v-for="(item, index) in rooms" :key="index">{{ item.room }}</view>
				</picker-view-column>
			</picker-view>

			<view style="margin-top: 20px; text-align: center;"><button type="primary" style="margin: 5rpx;" size="mini" @click="submit">提交</button></view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			userInfo: null,
			showPickerView: true,
			address: null,
			dorms: [], // ['二区15舍', '三区26舍']
			rooms: [], // [309, 310]
			values: [0, 0],
			addressTree: null // {'二区15舍': [Address对象]}
		};
	},
	onShow() {
		this.userInfo = uni.getStorageSync("userInfo")
	},
	onLoad() {
		this.getAddressTree();
	},
	methods: {
		getAddressTree() {
			let that = this;
			that.$request('/address/tree', 'get').then(result => {
				that.addressTree = result.data;
				let dorms = Object.keys(result.data);
				that.dorms = dorms;
				if (dorms.length > 0) {
					that.rooms = result.data[that.dorms[0]];
				}
			});
		},
		// 选择宿舍
		showPickerViewMethod() {
			this.showPickerView = !this.showPickerView;
			this.address = this.rooms[this.values[1]];
		},
		bindChange(e) {
			const val = e.detail.value; // 2个索引
			val[0] = val[0] ? val[0] : 0;
			val[1] = val[1] ? val[1] : 0;
			this.values = val;
			console.log('传入的值(2个索引 ): ', val);
			let dorm = this.dorms[val[0]]; // eg: 二区15舍
			this.rooms = this.addressTree[dorm];
			this.address = this.rooms[val[1]]; // eg: {room: 309, detail: '学生公寓2区15舍309'}
			console.log('地址:', JSON.stringify(this.address));
		},
		submit() {
			let that = this;
			if (!this.address || !this.address.dorm || !this.address.room) {
				that.$msg('请选择地址');
				return false;
			}

			uni.showModal({
				content: '选择寝室后将无法修改，确认无误？',
				success(e) {
					if (e.confirm) {
						that.$request('/student/address/' + that.address.id, 'put').then(result => {
							that.userInfo.addressId = result.data.id;
							that.userInfo.address = result.data;
							uni.setStorageSync("userInfo", that.userInfo)
							uni.reLaunch({
								url: '/pages/me/index'
							})
						});
					}
				}
			});
		}
	}
};
</script>
<style>
picker-view {
	width: 100%;
	height: 600rpx;
	margin-top: 20rpx;
}
.item {
	line-height: 100rpx;
	text-align: center;
}
</style>
